<?php

namespace app\admin\controller;

use app\admin\validate\Product;
use app\common\model\ProductImage;
use app\common\model\ProductStock;
use app\common\model\ProductsType;
use app\common\model\Products as ProductModel;
use app\common\model\ShopsDepartment;

class Products extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->isLogin();
    }

//    是否添加商品是同步上传规格
    private $is_edit_stock = true;
    /**
     * @route('products/shopsproduct')
     * 商店商品列表
     */
    public function shopsproduct()
    {
        // 获取搜索条件
        $get['shop_name'] = input('get.shop_name');
        $get['state'] = input('get.state');
        $where = null;
        if($this->_shopid){
            $where[] = ['p.shop_id','=',$this->_shopid];
        }
//        判断用户类型
        $isdisplay = true;

        $isshop = $this->_shopid;
        if($isshop != 0){
            $isdisplay = false;
        }
        if(!empty($get['state'])){
            $where[] = ['p.state','=',$get['state']];
        }
        if(!empty($get['shop_name'])){
            $where[] = ['s.shop_name','like',"%".$get['shop_name']."%"];
        }
        $where[] = ['p.is_del','=',1];
        $where[] = ['p.class_id','=',1];
        // 后台账号数据
		$model = new ProductModel();
        $rs_data = $model
            ->alias('p')
            ->leftJoin('ddt_shops s','s.shop_id = p.shop_id')
            ->leftjoin('ddt_products_type pt','pt.type_id = p.type_id')
            ->where($where)
            ->field('p.*,s.shop_name,pt.type_name')
            ->order('p.product_id desc')
            ->paginate($this->limit);

//        var_dump($subplatforms);die;
        $tvar = array(
            "title" => "商品列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('products/shopsproduct');
    }

    /**
     * @route('products/boxeproduct')
     * 添加编辑商品
     */
    public function Boxeproduct()
    {

        $model = new ProductModel();
        $typeMdodel = new ProductsType();

        if(request()->isAjax()){

            $param = input();

            $validate = new Product();
            $checkres = $validate->scene('EditProduct')->check($param);
            if (!$checkres) {
                $this->error($validate->getError());
            }

//            $product_id = $this->regpost("product_id","int",0);
//            $type_id = $this->regpost("type_id","int");
//            $price = $this->regpost("price","float");
//            $mprice = $this->regpost("mprice","float");
//            $sprice = $this->regpost("sprice","float");

            $product_id = $param['product_id'];
            $type_id = $param['type_id'];
            $price = $param['price'];
            $mprice = $param['mprice'];
            $sprice = $param['sprice'];

            $type = $typeMdodel->where('type_id','=',$type_id)->where('is_del','=',1)->find();

            if($price < $mprice || $price < $sprice){
                $this->error("商品原价不能小于会员价和销售价");
            }
            if(empty($type)){
                $this->error("不存在该分类");
            }
            if($this->_shopid != 0){
                $approved = 1;
            } else {
                $approved = 2;
            }

            $param = [
                "product_name" => $param['product_name'],
                "imageurl" => $param['imageurl'],
                "express_fee" => $param['express_fee'],
                "state" => $param['state'],
                "describe" => $param['describe'],
                "sort" => $param['sort'],
                "type_id" => $type_id,
                "price" => $price,
                "mprice" => $mprice,
                "sprice" => $sprice,
                "admin_id" => $this->_userid,
                "shop_id" => $this->_shopid,
                "approved" => $approved,
//                "growth_coin" => $param['growth_coin'],
            ];
            if($this->_shopid == 0){
                unset($param['shop_id']);
            }

//            var_dump($param);die;


            if($product_id == 0){
                $rs = $model->edit($param);
            } else {
                $rs = $model->edit($param,$product_id);
            }
            if($rs === false){
                $this->error($model->getError());
            }
            $this->success('操作成功','/products/shopsproduct');
        }

        $typelist = $typeMdodel->get_tree();
//        echo "<pre>";
//        var_dump($typelist);die;
        $product_id = $_GET['product_id'];
        $product = null;
        $tvar = array(
            "title" => "添加商品",
            "time"  => time(),
            "product_id"   => $product_id,
            "typelist" => $typelist,
        );
        if($product_id != 0){
            $tvar["title"] = "编辑商品";
            $product = $model->where('product_id','=',$product_id)->find();
        }

        $this->assign("data", $tvar);
        $this->assign("product", $product);
        return $this->fetch('products/boxeproduct');
    }

    /**
     * @route('products/exchangeproduct')
     * 兑换商品列表
     */
    public function exchangeproduct()
    {
        // 获取搜索条件
        $get['shop_name'] = input('get.shop_name');
        $get['state'] = input('get.state');

        $where = [
            'state' => $get['state'],
            'shop_name' => $get['shop_name'],
            'is_del' => 1,
            'class_id' => 2,
        ];
        $isdisplay = true;
        $is_edit_stock = $this->is_edit_stock;
        $isshop = $this->_shopid;
        if($isshop != 0){
            $where['shop_id'] = $this->_shopid;
            $isdisplay = false;
        }
        $productsModel = new ProductModel();
        // 后台账号数据
        $rs_data = $productsModel->admin_get_list($where,'','p.*,s.shop_name,pt.type_name',$this->limit);
        if($is_edit_stock){
            $stockModel = new ProductStock();
            $rs_data = $rs_data->each(function($items) use($is_edit_stock,$stockModel){
                $condition = [
                    "product_id" => $items['product_id'],
                    "is_del" => 1,
                ];
                $stocks = $stockModel->get_stock_list($condition,'*');
                $items['p_s_id'] = $stocks[0]['p_s_id'];
                $items['p_s_name'] = $stocks[0]['p_s_name'];
                $items['stock'] = $stocks[0]['stock'];
                return $items;
            });
        }
//        var_dump($rs_data);die;
        $tvar = array(
            "title" => "兑换商品列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
            "is_edit_stock" => $is_edit_stock,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('products/exchangeproducts/shopsproduct');
    }


    /**
     * @route('products/boxexchangeproduct')
     * 添加编辑兑换商品
     */
    public function BoxExchangeProduct()
    {

        $model = new ProductModel();
        $typeMdodel = new ProductsType();

        $is_edit_stock = $this->is_edit_stock;
        $stockModel = $is_edit_stock? new ProductStock() :"";
        if(request()->isAjax()){

            $param = input();

//            var_dump(234);die;
            $validate = new Product();
            if($is_edit_stock){
                $checkres = $validate->scene('NewExchangeProduct')->check($param);
            } else {
                $checkres = $validate->scene('ExchangeProduct')->check($param);
            }
//            var_dump($checkres);die;
            if (!$checkres) {
                $this->error($validate->getError());
            }

            $product_id = $param['product_id'];
            $type_id = $param['type_id'];

            $type = $typeMdodel->where('type_id','=',$type_id)->where('type','=','online')->where('is_del','=',1)->find();

            if(empty($type)){
                $this->error("不存在该分类");
            }
            if($this->_shopid != 0){
                $approved = 1;
            } else {
                $approved = 2;
            }

            $data = [
//
                "product_name" => $param['product_name'],
                "imageurl" => $param['imageurl'],
//                "express_fee" => $param['express_fee'],
                "state" => $param['state'],
                "integral" => $param['integral'],
                "sort" => $param['sort'],

                "type_id" => $type_id,
                "admin_id" => $this->_userid,
                "shop_id" => $this->_shopid,
                "approved" => $approved,
                "class_id" => 2,
                "salecount" => $param['salecount'],
            ];
            if($this->_shopid == 0){
                unset($data['shop_id']);
            }
            if($is_edit_stock){
                $data["describe"] = $param['describe'];
            }

            $model->startTrans();
            if($product_id == 0){
                $rs = $model->edit($data);
            } else {
                $rs = $model->edit($data,$product_id);
            }
            if($rs === false){
                $this->error($model->getError());
            }
            if($is_edit_stock){
                $stock_id = $param['stock_id'];
                $s_data = [
                    'p_s_name' => $param['stock_name'],
                    'product_id' => $rs,
                    'stock' => $param['stock_number'],
                ];
                if($stock_id == 0){
                    $s_rs = $stockModel->edit($s_data);
                } else {
                    $s_rs = $stockModel->edit($s_data,$stock_id);
                }
                if($s_rs === false){
                    $model->rollback();
                    $this->error($stockModel->getError());
                }
            }
            $model->commit();
            $this->success('操作成功','/products/exchangeproduct');
        }

        $typelist = $typeMdodel->get_tree();
//        echo "<pre>";
//        var_dump($typelist);die;
        $product_id = $_GET['product_id'];
        $product = null;
        $tvar = array(
            "title" => "添加兑换商品",
            "time"  => time(),
            "product_id"   => $product_id,
            "typelist" => $typelist,
            "is_edit_stock" => $is_edit_stock,
        );
        if($product_id != 0){
            $tvar["title"] = "编辑兑换商品";
            $product = $model->where('product_id','=',$product_id)->find();
        }
        if($is_edit_stock){
            $stock_id = $_GET['stock_id'];
            $tvar["stock_id"] = $stock_id;
            $stock = null;
            if($stock_id != 0){
                $stock = $stockModel->getOneStock($product_id,$stock_id);
            }
            $this->assign("stock",$stock);
        }

        $this->assign("data", $tvar);
        $this->assign("product", $product);
        return $this->fetch('products/exchangeproducts/boxeproduct');
    }

    /**
     * @route('products/loveproduct')
     * 爱心餐商品列表
     */
    public function loveproduct()
    {
        // 获取搜索条件
        $get['shop_name'] = input('get.shop_name');
        $get['state'] = input('get.state');

        $where = [
            'state' => $get['state'],
            'shop_name' => $get['shop_name'],
            'is_del' => 1,
            'class_id' => 3,
        ];
        $isdisplay = true;
        $is_edit_stock = $this->is_edit_stock;
        $isshop = $this->_shopid;
        if($isshop != 0){
            $where['shop_id'] = $this->_shopid;
            $isdisplay = false;
        }
        $productsModel = new ProductModel();
        // 后台账号数据
        $rs_data = $productsModel->admin_get_list($where,'','p.*,s.shop_name,pt.type_name',$this->limit);

        if($is_edit_stock){
            $stockModel = new ProductStock();
            $rs_data = $rs_data->each(function($items) use($is_edit_stock,$stockModel){
                $condition = [
                    "product_id" => $items['product_id'],
                    "is_del" => 1,
                ];
                $stocks = $stockModel->get_stock_list($condition,'*');
                if(!empty($stocks)){
                    $items['p_s_id'] = $stocks[0]['p_s_id'];
                    $items['p_s_name'] = $stocks[0]['p_s_name'];
                    $items['stock'] = $stocks[0]['stock'];
                }
                return $items;
            });
        }
//        var_dump($rs_data);die;
        $tvar = array(
            "title" => "爱心餐列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
            "is_edit_stock" => $is_edit_stock,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('products/loveproducts/shopsproduct');
    }


    /**
     * @route('products/boxloveproduct')
     * 添加编辑爱心餐商品
     */
    public function BoxLoveProduct()
    {

        $model = new ProductModel();
        $typeMdodel = new ProductsType();

        $is_edit_stock = $this->is_edit_stock;
        $stockModel = $is_edit_stock? new ProductStock() :"";
        if(request()->isAjax()){

            $param = input();
//            var_dump(234);die;
            $validate = new Product();
            if($is_edit_stock){
                $checkres = $validate->scene('LoveProduct')->check($param);
            } else {
                $checkres = $validate->scene('LoveProduct')->check($param);
            }
//            var_dump($checkres);die;
            if (!$checkres) {
                $this->error($validate->getError());
            }

            $product_id = $param['product_id'];
            $type_id = $param['type_id'];

            $type = $typeMdodel->where('type_id','=',$type_id)->where('is_del','=',1)->find();

            if(empty($type)){
                $this->error("不存在该分类");
            }
            if($this->_shopid != 0){
                $approved = 1;
            } else {
                $approved = 2;
            }

            $data = [
//
                "product_name" => $param['product_name'],
                "imageurl" => $param['imageurl'],
                "state" => $param['state'],
                "sort" => $param['sort'],

                "type_id" => $type_id,
                "admin_id" => $this->_userid,
                "shop_id" => $this->_shopid,
                "approved" => $approved,
                "class_id" => 3,
            ];
            if($this->_shopid == 0){
                unset($data['shop_id']);
            }
//            var_dump($param);die;

            $model->startTrans();
            if($product_id == 0){
                $rs = $model->edit($data);
            } else {
                $rs = $model->edit($data,$product_id);
            }
            if($rs === false){
                $this->error($model->getError());
            }
            if($is_edit_stock){
                $stock_id = $param['stock_id'];
                $s_data = [
                    'p_s_name' => $param['stock_name'],
                    'product_id' => $rs,
                    'stock' => $param['stock_number'],
                ];
                if($stock_id == 0){
                    $s_rs = $stockModel->edit($s_data);
                } else {
                    $s_rs = $stockModel->edit($s_data,$stock_id);
                }
                if($s_rs === false){
                    $model->rollback();
                    $this->error($stockModel->getError());
                }
            }
            $model->commit();
            $this->success('操作成功','/products/loveproduct');
        }

        $typelist = $typeMdodel->get_tree();
//        echo "<pre>";
//        var_dump($typelist);die;
        $product_id = $_GET['product_id'];
        $product = null;
        $tvar = array(
            "title" => "添加爱心餐商品",
            "time"  => time(),
            "product_id"   => $product_id,
            "typelist" => $typelist,
            "is_edit_stock" => $is_edit_stock,
        );
        if($product_id != 0){
            $tvar["title"] = "编辑爱心餐商品";
            $product = $model->where('product_id','=',$product_id)->find();
        }
        if($is_edit_stock){
            $stock_id = $_GET['stock_id'];
            $tvar["stock_id"] = $stock_id;
            $stock = null;
            if($stock_id != 0){
                $stock = $stockModel->getOneStock($product_id,$stock_id);
            }
            $this->assign("stock",$stock);
        }

        $this->assign("data", $tvar);
        $this->assign("product", $product);
        return $this->fetch('products/loveproducts/boxeproduct');
    }

    /**
     * @route('products/teamproduct')
     * 团餐商品列表
     */
    public function teamproduct()
    {
        // 获取搜索条件
        $get['shop_name'] = input('get.shop_name');
        $get['state'] = input('get.state');

        $where = [
            'state' => $get['state'],
            'shop_name' => $get['shop_name'],
            'is_del' => 1,
            'class_id' => 4,
        ];
        $isdisplay = true;
        $isshop = $this->_shopid;
        if($isshop != 0){
            $where['shop_id'] = $this->_shopid;
            $isdisplay = false;
        }
        $productsModel = new ProductModel();
        // 后台账号数据
        $rs_data = $productsModel->admin_get_list($where,'','p.*,s.shop_name,pt.type_name',$this->limit);

//        var_dump($rs_data);die;
        $tvar = array(
            "title" => "团餐列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('products/teamproducts/shopsproduct');
    }


    /**
     * @route('products/boxteamproduct')
     * 添加编辑团餐商品
     */
    public function BoxTeamProduct()
    {

        $model = new ProductModel();
        $typeMdodel = new ProductsType();

        if(request()->isAjax()){

            $param = input();
//            var_dump(234);die;
            $validate = new Product();
            $checkres = $validate->scene('TeamProduct')->check($param);
//            var_dump($checkres);die;
            if (!$checkres) {
                $this->error($validate->getError());
            }

            $product_id = $param['product_id'];
            $type_id = $param['type_id'];

            $type = $typeMdodel->where('type_id','=',$type_id)->where('is_del','=',1)->find();

            if(empty($type)){
                $this->error("不存在该分类");
            }
            if($this->_shopid != 0){
                $approved = 1;
            } else {
                $approved = 2;
            }

            $param = [
                "product_name" => $param['product_name'],
                "imageurl" => $param['imageurl'],
                "state" => $param['state'],
                "sort" => $param['sort'],
                "type_id" => $type_id,
                "price" => $param['price'],
                "mprice" => $param['mprice'],
                "sprice" => $param['sprice'],
                "describe" => $param['describe'],
                "admin_id" => $this->_userid,
                "shop_id" => $this->_shopid,
                "approved" => $approved,
                "class_id" => 4,
//                "growth_coin" => $param['growth_coin'],
                "salecount" => $param['salecount'],
            ];
            if($this->_shopid == 0){
                unset($param['shop_id']);
            }

            if($product_id == 0){
                $rs = $model->edit($param);
            } else {
                $rs = $model->edit($param,$product_id);
            }
            if($rs === false){
                $this->error($model->getError());
            }
            $this->success('操作成功','/products/teamproduct');
        }

        $typelist = $typeMdodel->get_tree();
        $product_id = $_GET['product_id'];
        $product = null;
        $tvar = array(
            "title" => "添加团餐商品",
            "time"  => time(),
            "product_id"   => $product_id,
            "typelist" => $typelist,
        );
        if($product_id != 0){
            $tvar["title"] = "编辑团餐商品";
            $product = $model->where('product_id','=',$product_id)->find();
        }

        $this->assign("data", $tvar);
        $this->assign("product", $product);
        return $this->fetch('products/teamproducts/boxeproduct');
    }

    /**
     * @route('products/delproduct')
     * 商品删除
     */
    public function UpdateState()
    {
        $productid = input('productid');
        $model = new ProductModel();
        $where['product_id'] = $productid;
        $where['is_del'] = 1;
        if($this->_shopid != 0){
            $where['shop_id'] = $this->_shopid;
        }
        $product = $model->where($where)->find();

        if(empty($product)){
            $this->error('不存在该商品');
        }
        $param['is_del'] = 2;
        $rs2 = $model->edit($param,$productid);
        if($rs2 === false){
            $this->error("操作失败");
        }
        $this->success('操作成功');
    }

    /**
     * @route('products/productstock')
     * 商品库存列表
     */
    public function productstock()
    {
        $get['product_id'] = input('get.product_id');
        $model = new ProductModel();
        $stockModel = new ProductStock();
        $where['p.product_id'] = $get['product_id'];
        $where['p.is_del'] = 1;
        if($this->_shopid != 0){
            $where['p.shop_id'] = $this->_shopid;
        }
        $product = $model
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->where($where)
            ->field('p.*,s.shop_name')
//            ->buildSql();
            ->find();
//        var_dump($product->toArray());die;
        if(empty($product)){
            $this->error('不存在该商品','/products/shopsproduct');
        }
        if($product->toArray()['class_id'] == 4){
            $is_show = false;
        } else {
            $is_show = true;
        }
        $rs_data = $stockModel->where('product_id','=',$get['product_id'])->where('is_del','=',1)->paginate($this->limit);
//        var_dump(123);die;
        $tvar = array(
            "title" => "商品库存列表",
            "time"  => time(),
            "stock"  => $rs_data,
            "get"   => $get,
            "is_show" => $is_show,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign("product", $product->toArray());
        $this->assign('page', $page);
        return $this->fetch('products/productstock');
    }

    /**
     * @route('products/boxestock')
     * 添加编辑商品库存
     */
    public function BoxeStock()
    {
        $model = new ProductStock();
        $pmodel = new ProductModel();
        $get['stock_id'] = input('get.stock_id');
        $get['product_id'] = input('product_id');
        if(input('handle') == "upload"){
            $res = \Upload::FileUpload('file','productimages',1024*1024*10,'jpg,png,jpeg,gif');
            if(!$res['data']){
                $this->result([],-1,$res['msg']);
            }
            $this->result($res['data']['file_path'],1);
        }
        $product_id = $get['product_id'];
        $where['product_id'] = $product_id;
        $where['is_del'] = 1;
        if($this->_shopid != 0){
            $where['shop_id'] = $this->_shopid;
        }
        $product = $pmodel->where($where)->find();
        if(!$product){
            $this->error('不存在该商品','/products/shopsproduct');
        }
        if(request()->isAjax()){
            $stock_id = input("post.stock_id",0);
            $getdata = $product->toArray();
            if($stock_id != 0){
                $stock = $model->where('p_s_id','=',$stock_id)->where('is_del','=',1)->find();
                if(!$stock){
                    $this->error('不存在的商品规格','/products/productstock?product_id='.$product_id);
                }
            }
            else {
                $stock = $model->where('product_id','=', $getdata['product_id'])->where('is_del','=',1)->select()->toArray();
                if($stock && $getdata['class_id'] == 4){
                    $this->error('该类型商品只能上传一个规格','/products/productstock?product_id='.$product_id);
                }
            }
            $data['product_id'] = $getdata['product_id'];
//            var_dump(123);die;
            if($product['class_id'] == 4) {
                $data['g_m_details'] = input("g_m_details");
                $data['g_m_paper'] = input("post.g_m_paper", "string");
            }
            $data['p_s_name'] = input("post.stock_name", "string");
            $data['stock'] = input("post.stock_number","string");
//            var_dump($data);die;
            $model->startTrans();
            $rs = $model->edit($data,$stock_id);
            if($rs === false){
                $model->rollback();
                $this->error($model->getError());
            }
            if($this->_shopid != 0) {
                $result = $pmodel->edit(array("approved"=>1),$product_id);
                if($result === false){
                    $model->rollback();
                    $this->error($pmodel->getError());
                }
            }
            $model->commit();
            $this->success('操作成功','/products/productstock?product_id='.$product_id);
        }
        $stock = null;
        $showdetails = false;
        if($product['class_id'] == 4){
            $showdetails = true;
        }
        if($get['stock_id'] != 0){
            $stock = $model->where('p_s_id','=',$get['stock_id'])->find();
        }
//        var_dump($checkdetail);
        $tvar = array(
            "title" => "添加商品库存",
            "time"  => time(),
            "stock_id" => $get['stock_id'],
            "product_id" => $get['product_id'],
            "is_show" => $showdetails,
        );
//        var_dump($get['stock_id']);die;
        if($get['stock_id'] != 0){
            $tvar['title'] = "编辑商品库存";
        }
        $this->assign("data", $tvar);
        $this->assign("stock", $stock);
        return $this->fetch('products/boxestock');
    }


    /**
     * @route('products/delstock')
     * 商品库存删除
     */
    public function DelStock()
    {
        $stockid = input('stock_id');
        $model = new ProductStock();
        $where['p_s_id'] = $stockid;
        $where['s.is_del'] = 1;
        if($this->_shopid != 0){
            $where['p.shop_id'] = $this->_shopid;
        }
        $stock = $model
            ->alias('s')
            ->leftJoin('ddt_products p','s.product_id = p.product_id')
            ->where($where)
            ->field('s.*')
            ->find();
//        var_dump($stock);die;
        if(!$stock){
            $this->error('不存在该商品的库存');
        }
        $param['is_del'] = 2;
        $rs2 = $model->edit($param,$stockid);
        if($rs2 === false){
            $this->error("操作失败");
        }
        $this->success('操作成功');
    }


    /**
     * @route('products/productimage')
     * 商品图库列表
     */
    public function productimage()
    {
        $get['product_id'] = input('get.product_id');
        $model = new ProductModel();
        $imageModel = new ProductImage();
        $where['p.product_id'] = $get['product_id'];
        $where['p.is_del'] = 1;
        $isdisplay = true;
        if($this->_shopid != 0){
            $isdisplay = false;
            $where['p.shop_id'] = $this->_shopid;
        }
        $product = $model
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->where($where)
            ->field('p.*,s.shop_name')
//            ->buildSql();
            ->find();
//        var_dump($product->toArray());die;
        if(empty($product)){
            $this->error('不存在该商品','/products/shopsproduct');
        }
        $rs_data = $imageModel->where('product_id','=',$get['product_id'])->order('sort', 'asc')->paginate($this->limit);
//        var_dump(123);die;
        $tvar = array(
            "title" => "商品库存列表",
            "time"  => time(),
            "images"  => $rs_data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign("product", $product->toArray());
        $this->assign('page', $page);
        return $this->fetch('products/productimage');
    }

    /**
     * @route('products/showimage')
     * 商品图片显示隐藏
     */
    public function ShowImage()
    {
        $imageid = input('imageid');
        $model = new ProductImage();
        $where['image_id'] = $imageid;
        if($this->_shopid != 0){
            $where['p.shop_id'] = $this->_shopid;
        }
        $image = $model
            ->alias('i')
            ->leftJoin('ddt_products p','i.product_id = p.product_id')
            ->where($where)
            ->field('i.*')
            ->find();
//        var_dump($stock);die;
        if(!$image){
            $this->error('不存在该图片');
        }
        $data = $image->toArray();
        if($data['is_show'] == 0){
            $param['is_show'] = 1;
        } else {
            $param['is_show'] = 0;
        }
        $rs2 = $model->edit($param,$imageid);
        if($rs2 === false){
            $this->error("操作失败");
        }
        $this->success('操作成功');
    }

    /**
     * @route('products/boxeimage')
     * 添加编辑商品图库
     */
    public function BoxeImage()
    {
        $model = new ProductImage();
        $pmodel = new ProductModel();
        $get['image_id'] = input('get.image_id');
        $get['product_id'] = input('get.product_id');
        if(request()->isAjax()){
            $image_id = input("post.image_id",0);
            $product_id = input("post.product_id");
            $is_show = input('is_show');
            if($is_show != 0 && $is_show != 1){
                $this->error('参数有误');
            }
            if($image_id != 0){
                $image = $model->where('image_id','=',$image_id)->find();
                if(!$image){
                    $this->error('不存在的商品图片','/products/productimage?product_id='.$product_id);
                }
            }
            $where['product_id'] = $product_id;
            $where['is_del'] = 1;
            if($this->_shopid != 0){
                $where['shop_id'] = $this->_shopid;
            }
            $product = $pmodel->where($where)->find();
            if(!$product){
                $this->error('不存在该商品','/products/shopsproduct');
            }
            $getdata = $product->toArray();
            $data['product_id'] = $getdata['product_id'];
////            var_dump(123);die;
            $data['url'] = input("post.imageurl");
            $data['sort'] = input("post.sort");
            $data['is_show'] = $is_show;
//            var_dump($data);die;
            $model->startTrans();
            $rs = $model->edit($data,$image_id);
            if($rs === false){
                $model->rollback();
                $this->error($model->getError());
            }
            if($this->_shopid != 0) {
                $result = $pmodel->edit(array("approved"=>1),$product_id);
                if($result === false){
                    $model->rollback();
                    $this->error($pmodel->getError());
                }
            }
            $model->commit();
            $this->success('操作成功','/products/productimage?product_id='.$product_id);
        }
        $image = null;
        if($get['image_id'] != 0){
            $image = $model->where('image_id','=',$get['image_id'])->find();
        }
//        var_dump($checkdetail);
        $tvar = array(
            "title" => "添加商品图片",
            "time"  => time(),
            "image_id" => $get['image_id'],
            "product_id" => $get['product_id'],
        );
//        var_dump($get['stock_id']);die;
        if($get['image_id'] != 0){
            $tvar['title'] = "编辑商品图片";
        }
        $this->assign("data", $tvar);
        $this->assign("images", $image);
        return $this->fetch('products/boxeimage');
    }

	/**
	 * @route('products/productsonlinetypelist')
	 * 线上商品分类列表
	 */
	public function productsonlinetypelist(){
		$isdisplay = false;
		// 获取搜索条件
		//总部商铺ID为0，总部可以看到所有商品
		if($this->_shopid != 0){
			//商家身份只能看自己的
			$get['shop_id'] = $this->_shopid;
			//页面的搜索显示
			$isdisplay = true;
		}else{
			//总部的搜索功能
			$get['shop_id'] = input('get.shop_id');
		}
		$get['type_name'] = input('get.type_name');
		$get['type'] = 'online';
		$get['is_del'] = 1;
		$field = 'type_id,p_id,type_name,sort,add_time,is_del';
		$order = 'p_id asc,sort asc';

		$Model = new ProductsType();
		$fdata = $Model->get_tree($field,$get,$order);

		$data = [];
		foreach ($fdata as $key => $value){
			if(array_key_exists("type_id", $value)){
				$data[] = [
					'type_id' => $value['type_id'],
					'p_id' => $value['p_id'],
					'type_name' => $value['type_name'],
					'sort' => $value['sort'],
					'add_time' => $value['add_time'],
				];

				if(count($value['children']) > 0){
					foreach ($value['children'] as $k => $v){
						$data[] = [
							'type_id' => $v['type_id'],
							'p_id' => $v['p_id'],
							'type_name' => $v['type_name'],
							'sort' => $v['sort'],
							'add_time' => $v['add_time'],
						];
					}
				}
			}

		}

		$tvar = array(
			"title" => "商品分类列表",
			"time"  => time(),
			"data"  => $data,
			"get"   => $get,
			"isdisplay" => $isdisplay,
		);
//		print_r($tvar);die;
		$this->assign("data", $tvar);
		return $this->fetch('products/productsonlinetypelist');
	}

	/**
	 * @route('products/productsofflinetypelist')
	 * 线下商品分类列表
	 */
	public function productsofflinetypelist(){
		$isdisplay = false;
		// 获取搜索条件
		//总部商铺ID为0，总部可以看到所有商品
		if($this->_shopid != 0){
			//商家身份只能看自己的
			$get['shop_id'] = $this->_shopid;
			//页面的搜索显示
			$isdisplay = true;
		}else{
			//总部的搜索功能
			$get['shop_id'] = input('get.shop_id');
		}
		$get['type_name'] = input('get.type_name');
		$get['type'] = 'offline';
		$get['is_del'] = 1;
		$field = 'type_id,p_id,type_name,sort,add_time,is_del';
		$order = 'p_id asc,sort asc';

		$Model = new ProductsType();
		$fdata = $Model->get_tree($field,$get,$order,'offline');

		$data = [];
		foreach ($fdata as $key => $value){
			if(array_key_exists("type_id", $value)){
				$data[] = [
					'type_id' => $value['type_id'],
					'p_id' => $value['p_id'],
					'type_name' => $value['type_name'],
					'sort' => $value['sort'],
					'add_time' => $value['add_time'],
				];

				if(count($value['children']) > 0){
					foreach ($value['children'] as $k => $v){
						$data[] = [
							'type_id' => $v['type_id'],
							'p_id' => $v['p_id'],
							'type_name' => $v['type_name'],
							'sort' => $v['sort'],
							'add_time' => $v['add_time'],
						];
					}
				}
			}

		}

		$tvar = array(
			"title" => "商品分类列表",
			"time"  => time(),
			"data"  => $data,
			"get"   => $get,
			"isdisplay" => $isdisplay,
		);
//		print_r($tvar);die;
		$this->assign("data", $tvar);
		return $this->fetch('products/productsofflinetypelist');
	}

    /**
     * 添加分类
     * @route('products/boxeproducttype')
     */
    public function BoxeProductType(\think\Request $request)
    {
        $id = input('id');
        $ProductType = new ProductsType();

        if(request()->isAjax()){
            $param = $request->param();

			$params['p_id'] = $param['typeid'];
			$params['type'] = 'online';
            $params['type_name'] = $param['type_name'];
            $params['sort'] = $param['sort'];
            $params['admin_id'] = $this->_userid;

            $rs = $ProductType->edit($params, $param['id']);
            if($rs === false){
                $this->error('操作失败');
            }
            $this->success('操作成功');
        }

        $cond['shop_id'] = 0;
        $cond['pid'] = 0;
		$cond['type'] = 'online';
        $type_data = $ProductType->get_list('type_id, type_name', $cond);

        $data = null;
        if($id > 0){
            $data = $ProductType->getOne(['type_id' => $id],'type_id,p_id,type_name,sort');
        }

        $tvar = array(
            "title" => "添加商品分类",
            "time"  => time(),
            'type_data' => $type_data,
            "id" => $id,
            "data" => $data
        );
        $this->assign("data", $tvar);
        return $this->fetch('products/boxeproducttype');
    }

	/**
	 * 添加分类
	 * @route('products/boxeofflineproducttype')
	 */
	public function BoxeofflineProductType(\think\Request $request)
	{
		$id = input('id');
		$ProductType = new ProductsType();

		if(request()->isAjax()){
			$param = $request->param();

			$params['p_id'] = $param['typeid'];
			$params['type'] = 'offline';
			$params['type_name'] = $param['type_name'];
			$params['sort'] = $param['sort'];
			$params['admin_id'] = $this->_userid;

			$rs = $ProductType->edit($params, $param['id']);
			if($rs === false){
				$this->error('操作失败');
			}
			$this->success('操作成功');
		}

		$cond['shop_id'] = 0;
		$cond['pid'] = 0;
		$cond['type'] = 'offline';
		$type_data = $ProductType->get_list('type_id, type_name', $cond);

		$data = null;
		if($id > 0){
			$data = $ProductType->getOne(['type_id' => $id],'type_id,p_id,type_name,sort');
		}

		$tvar = array(
			"title" => "添加商品分类",
			"time"  => time(),
			'type_data' => $type_data,
			"id" => $id,
			"data" => $data
		);
		$this->assign("data", $tvar);
		return $this->fetch('products/boxeofflineproducttype');
	}

    /**
     * 删除分类
     * @route('products/delproducttype')
     */
    public function delproducttype()
    {
        $id = input('id');

		$ProductType = new ProductsType();
		$type = $ProductType->where('type_id','=',$id)->find();
		if(!empty($type)){
		    $productModel = new ProductModel();
		    if($type['p_id'] == 0){
                $typesql = "type_id in (select type_id from ddt_products_type where p_id = {$type['type_id']})";
            } else {
		        $typesql = "type_id = {$type['type_id']}";
            }
            $count = $productModel
                ->where('is_del','=',1)
                ->where('approved','=',2)
                ->where('state','=',1)
                ->where($typesql)
                ->count();
		    if($count > 0){
                $this->error("该分类下还有{$count}件商品");
            }
        }
		$rs = $ProductType->Del($id);
        if($rs === false){
            $this->error('操作失败');
        }
        $this->success('操作成功');

    }

	/**
	 * @route('products/offlineproductlist')
	 * 点餐商品列表
	 */
	public function offlineproductlist()
	{
		// 获取搜索条件
		$get['shop_name'] = input('get.shop_name');
		$get['product_name'] = input('get.product_name');
		$get['state'] = input('get.state');
		if($this->_shopid){
			$get['shop_id'] = $this->_shopid;
		}
//        判断用户类型
		$isdisplay = true;

		$isshop = $this->_shopid;
		if($isshop != 0){
			$isdisplay = false;
		}
		// 后台账号数据
		$model = new ProductModel();
		$item = 'p.*,s.shop_name,pt.type_name,d.department_name';
		$orderby = 'p.product_id desc';
		$join = [
            ['ddt_shops s','s.shop_id = p.shop_id'],
            ['ddt_products_type pt','pt.type_id = p.type_id'],
            ['ddt_shops_department d','p.department_id = d.department_id']
        ];
		$get['is_del'] = 1;
		$get['class_id'] = 5;
//		var_dump($get);
		$rs_data = $model->admin_get_list($get,$orderby,$item,$this->limit,$join);

//        var_dump($subplatforms);die;

		$tvar = array(
			"title" => "点餐商品列表",
			"time"  => time(),
			"data"  => $rs_data,
			"get"   => $get,
			"isdisplay" => $isdisplay,
		);
		$page = $rs_data->render();
		$this->assign("data", $tvar);
		$this->assign('page', $page);
		return $this->fetch('products/offlineproducts/shopsproduct');
	}

    /**
     * @route('products/boxofflineproduct')
     * 添加编辑线下商品
     */
    public function BoxOfflineProduct()
    {
        $model = new ProductModel();
		$typeMdodel = new ProductsType();
        $departmentModel = new ShopsDepartment();

        if(request()->isAjax()){

            $param = input();

            $validate = new Product();
            $checkres = $validate->scene('OfflineProduct')->check($param);
            if (!$checkres) {
                $this->error($validate->getError());
            }

            $product_id = $param['product_id'];
            $sprice = $param['sprice'];

            if($this->_shopid != 0){
                $approved = 1;
            } else {
                $approved = 2;
            }

            $param = [
                "product_name" => $param['product_name'],
                "imageurl" => $param['imageurl'],
                "express_fee" => 0,
                "state" => $param['state'],
                "sort" => $param['sort'],
                "sprice" => $sprice,
                "admin_id" => $this->_userid,
                "shop_id" => $this->_shopid,
                "approved" => $approved,
                "class_id" => 5,
                "type_id" => $param['type_id'],
                "describe" => $param['describe'],
//                "growth_coin" => $param['growth_coin'],
            ];
            if($this->_shopid == 0){
                unset($param['shop_id']);
            }

            if($product_id == 0){
                $rs = $model->edit($param);
            } else {
                $rs = $model->edit($param,$product_id);
            }
            if($rs === false){
                $this->error($model->getError());
            }
            $this->success('操作成功','/products/offlineproductlist');
        }

        $product_id = $_GET['product_id'];
        $product = null;
		$typelist = $typeMdodel->get_tree('type_id,p_id,type_name,sort,add_time',['is_del' => 1], 'p_id asc,sort asc', 'offline');
        $tvar = array(
            "title" => "添加点餐商品",
            "time"  => time(),
            "product_id"   => $product_id,
			"typelist" => $typelist,
        );
        if($product_id != 0){
            $tvar["title"] = "编辑点餐商品";
            $product = $model->where('product_id','=',$product_id)->find();
        }
        $select_department_shop_id = $product_id != 0?$product['shop_id']:$this->_shopid;
        $departmentlist = $departmentModel->get_list('department_id,shop_id,department_name',['shop_id'=>$select_department_shop_id,'is_print_all'=>1]);
        $this->assign("data", $tvar);
        $this->assign("product", $product);
        $this->assign("departmentlist", $departmentlist);
        return $this->fetch('products/offlineproducts/boxeproduct');
    }

    /**
     * @route('products/showproductlist')
     * 展示菜品列表
     */
    public function showproductlist()
    {
        // 获取搜索条件
        $get['shop_name'] = input('get.shop_name');
        $get['state'] = input('get.state');
        $where = null;
        if($this->_shopid){
            $where[] = ['p.shop_id','=',$this->_shopid];
        }
//        判断用户类型
        $isdisplay = true;

        $isshop = $this->_shopid;
        if($isshop != 0){
            $isdisplay = false;
        }
        if(!empty($get['state'])){
            $where[] = ['p.state','=',$get['state']];
        }
        if(!empty($get['shop_name'])){
            $where[] = ['s.shop_name','like',"%".$get['shop_name']."%"];
        }
        $where[] = ['p.is_del','=',1];
        $where[] = ['p.class_id','=',6];
        // 后台账号数据
		$model = new ProductModel();
        $rs_data = $model
            ->alias('p')
            ->leftJoin('ddt_shops s','s.shop_id = p.shop_id')
            ->where($where)
            ->field('p.*,s.shop_name')
            ->order('p.product_id desc')
            ->paginate($this->limit);

//        var_dump($subplatforms);die;
        $tvar = array(
            "title" => "展示菜品列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('products/showproducts/productlist');
    }

    /**
     * @route('products/boxshowproduct')
     * 添加编辑展示商品
     */
    public function BoxShowProduct()
    {

        $model = new ProductModel();

        if(request()->isAjax()){

            $param = input();

            $validate = new Product();
            $checkres = $validate->scene('ShowProduct')->check($param);
            if (!$checkres) {
                $this->error($validate->getError());
            }

            $product_id = $param['product_id'];
            $price = $param['price'];
            if($this->_shopid != 0){
                $approved = 1;
            } else {
                $approved = 2;
            }

            $param = [
                "product_name" => $param['product_name'],
                "imageurl" => $param['imageurl'],
                "express_fee" => 0,
                "state" => $param['state'],
                "sort" => $param['sort'],
                "price" => $price,
                "admin_id" => $this->_userid,
                "shop_id" => $this->_shopid,
                "approved" => $approved,
                "class_id" => 6,
                "type_id" => 0,
            ];
            if($this->_shopid == 0){
                unset($param['shop_id']);
            }

//            var_dump($param);die;


            if($product_id == 0){
                $rs = $model->edit($param);
            } else {
                $rs = $model->edit($param,$product_id);
            }
            if($rs === false){
                $this->error($model->getError());
            }
            $this->success('操作成功','/products/offlineproductlist');
        }

        $product_id = $_GET['product_id'];
        $product = null;
        $tvar = array(
            "title" => "添加展示菜品",
            "time"  => time(),
            "product_id"   => $product_id,
        );
        if($product_id != 0){
            $tvar["title"] = "编辑展示菜品";
            $product = $model->where('product_id','=',$product_id)->find();
        }

        $this->assign("data", $tvar);
        $this->assign("product", $product);
        return $this->fetch('products/showproducts/boxeproduct');
    }
}